package com.sdses.weather.common;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sdses.weather.common.error.ErrCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * 重写API接口的基础返回类
 */
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private String code;
    private String message;
    private T data;

    public ApiResult(ErrCode re, T data) {
        this.code = re.getCode();
        this.message = re.getMsg();
        this.data = data;
    }
    @JsonIgnore
    public boolean isSuccess() {
        return ObjectUtil.equals(this.getCode(), ErrCode.SUCCESS.getCode()) || ObjectUtil.equals(this.getCode(), ErrCode.SUCCESS1000.getCode());
    }

    /**
     * 成功(code=0)
     * 示例: R.ok("登录成功")
     */
    public static <T> ApiResult<T> ok(T data) {
        return new ApiResult<T>(ErrCode.SUCCESS, data);
    }

    public static <T> ApiResult<T> fail(ErrCode err) {
        return new ApiResult<T>(err.getCode(), err.getMsg(), null);
    }

    public static <T> ApiResult<T> fail(String msg) {
        return new ApiResult<T>(ErrCode.FAILED.getCode(), msg, null);
    }

    public static <T> ApiResult<T> fail(String code, String msg) {
        return new ApiResult<T>(code, msg, null);
    }
}
